package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
* 分类管理
* */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /*
    * 新增分类
    * @param category
    * @return
    * */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /*
    * 分类的分页查询*/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        //1 创建分页构造器
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //2 创建条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //3 添加排序条件 以sort进行排序
        wrapper.orderByAsc(Category::getSort);
        //4 调用方法进行分页查询
        categoryService.page(categoryPage,wrapper);
        return R.success(categoryPage);
    }

    /*
    * 根据 id 删除分类*/
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除分类，id为：{}",id);
        //categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /*
    * 根据id修改分类信息*/
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //菜品分类的展示:根据条件查询分类数据  并以集合的方式进行展示
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //1 创建条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //2 添加查询条件
        queryWrapper.eq(category.getType() != null ,Category::getType,category.getType());
        //3 添加排序条件 : 按照sort排序字段进行升序排序,如果sort相同,再按照修改时间进行倒序排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //4 调用方法完成查询
        List<Category> list = categoryService.list(queryWrapper);
        //5 返回结果
        return R.success(list);
    }

}
